package nickthissen.iracing.activities;

import java.util.ArrayList;

import nickthissen.iracing.common.DataLoader;
import nickthissen.iracing.common.Error;
import nickthissen.iracing.common.Task;
import nickthissen.iracing.datamodels.Forum;
import nickthissen.iracing.datamodels.ForumList;
import nickthissen.iracing.adapters.ForumListAdapter;
import nickthissen.iracing.datamodels.Result;
import nickthissen.iracing.iracingforum2.R;
import nickthissen.iracing.networking.Networking;
import nickthissen.iracing.parsing.ForumListParser;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

public class ForumListActivity extends TaskItemListActivity<Forum>
{
	private static final String FORUMLIST = "FORUMLIST";
	
	private ActionBar actionBar;
	private ForumList forumList;
		
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.forumlist);
		
		// Set actionbar title
		actionBar = this.getSupportActionBar();
		actionBar.setTitle("Forum list");
		
		// Get forumlist object
        Bundle extras = savedInstanceState;
        if (extras == null)
        {
            Intent i = this.getIntent();
            extras = i.getExtras();
        }
		this.loadForumList(extras);
		
		this.setItems(forumList.Forums);
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getSupportMenuInflater().inflate(R.menu.forumlist, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId()) {
            case R.id.mnuRefresh:
                this.loadData();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

	@Override
	public void onSaveInstanceState(Bundle outState)
	{
		super.onSaveInstanceState(outState);
        outState.putSerializable(FORUMLIST, forumList);
	}

    @Override
    protected Task<?> createTask()
    {
        return new Task<Void>(this, dataLoader);
    }

    @Override
    protected void saveTaskInput(Bundle state)
    {

    }

    @Override
    protected Object restoreTaskInput(Bundle state)
    {
        return null;
    }

//    @Override
//	public void onRestoreInstanceState(Bundle state)
//	{
//		this.loadForumList(state);
//		super.onRestoreInstanceState(state);
//	}
	
	public static Intent getIntent(Context context, ForumList forumList)
	{
		Intent i = new Intent(context, ForumListActivity.class);
		i.putExtra(FORUMLIST, forumList);
		return i;
	}
	
	private void loadForumList(Bundle bundle)
	{
		Object obj = bundle.getSerializable(FORUMLIST);
		if (obj instanceof ForumList) 
		{
			forumList = (ForumList)obj;
		} 
		else 
		{
			Error e = new Error("Error communicating forum list.", "ForumList not passed to ForumListActivity.");
			e.report(this);
			
			forumList = new ForumList();
			forumList.Forums = new ArrayList<Forum>();
		}
	}
	
	@Override
	protected void setItems(ArrayList<Forum> items) 
	{
		ForumListAdapter adapter = new ForumListAdapter(this, R.layout.forumrow, items);
		this.setListAdapter(adapter);
	}

	@Override
	public void onItemClicked(Forum item) 
	{
		if (item.IsCategoryHeader) return;
		
		Intent intent = ThreadListActivity.getIntent(this, item.Id);
		this.startActivityForResult(intent, 0);
	}

	@Override
	protected void loadData()
    {
		startLoading("Refreshing forum list...", null, false);
	}

    private DataLoader<Void> dataLoader = new DataLoader<Void>()
    {
        public Result getData(Void in)
        {
            // Obtain forum list page source
            Result result = Networking.getForumList(this.getContext());

            if (result.Success)
            {
                // Parse source and return forumlist result
                String source = (String)result.Object;
                ForumListParser parser = new ForumListParser();
                parser.context = this.getContext();
                return parser.parse(source);
            }
            else
            {
                // Error
                return result;
            }
        }

        public void onFinished(Result out)
        {
            if (out.Success)
            {
                // Set forum items in list
                forumList = (ForumList)out.Object;
            }
            else
            {
                // Error
                forumList = new ForumList();
                forumList.Forums = new ArrayList<Forum>();

                Error error = Error.fromResult(out);
                error.report(this.getContext());
            }

            setItems(forumList.Forums);
            finishedLoading();
        }
    };
}
